#pragma once
#include <iostream>
#include <pthread.h>
#include <string>
#include <functional>
#include"Log.hpp"
namespace ThreadMoudle
{
    using func_t = std::function<void(std::string)>;//线程执行函数的类型对应HanlderTask
    class thread
    {
    public:
        thread(const std::string name, func_t func)
            : _name(name), _func(func)
        {}

        std::string Name()
        {
            return _name;
        }
        void Execute()
        {
            _isrunning = true;
            _func(_name);
            _isrunning = false;
        }

        static void *ThreadRoutine(void *args)
        {
            thread *self = static_cast<thread *>(args);
            self->Execute();
            return nullptr;
        }

        bool start()
        {
            int n = pthread_create(&_tid, nullptr, ThreadRoutine, this);
            if (n != 0)
                return false;
            else
                return true;
        }

        void stop()
        {
            if (_isrunning)
            {
                LOG(DEBUG,"%s stop",_name);
                pthread_cancel(_tid);
                _isrunning = false;
            }
        }
        
        void join()
        {
            pthread_join(_tid, nullptr);
           LOG(DEBUG,"%s join",_name);
        }

    private:
        pthread_t _tid;
        std::string _name;
        bool _isrunning;
        func_t _func;
    };
}